<?php
/**
 * 添加测试会员数据
 * 为最新注册的用户添加有效会员记录，以便测试应用创建功能
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/support/bootstrap.php';

use think\facade\Db;

echo "🔧 添加测试会员数据...\n";

try {
    // 获取最新注册的用户
    echo "📋 获取最新注册的用户...\n";
    $latestUser = Db::name('gf_et_users')
        ->order('id', 'desc')
        ->find();
    
    if (!$latestUser) {
        echo "❌ 未找到用户\n";
        exit(1);
    }
    
    echo "✅ 找到最新用户: ID={$latestUser['id']}, Email={$latestUser['email']}\n";
    
    // 检查是否已有会员记录
    $existingMembership = Db::name('gf_user_memberships')
        ->where('user_id', $latestUser['id'])
        ->find();
    
    if ($existingMembership) {
        echo "⚠️  用户已存在会员记录，更新为有效状态\n";
        
        // 更新现有记录
        Db::name('gf_user_memberships')
            ->where('user_id', $latestUser['id'])
            ->update([
                'plan_type' => 'basic',
                'status' => 'active',
                'start_date' => date('Y-m-d'),
                'end_date' => date('Y-m-d', strtotime('+1 year')),
                'auto_renew' => 1,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        
        echo "✅ 会员记录已更新\n";
    } else {
        echo "📋 创建新的会员记录...\n";
        
        // 创建新的会员记录
        $membershipData = [
            'user_id' => $latestUser['id'],
            'plan_type' => 'basic',
            'status' => 'active',
            'start_date' => date('Y-m-d'),
            'end_date' => date('Y-m-d', strtotime('+1 year')),
            'auto_renew' => 1,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        Db::name('gf_user_memberships')->insert($membershipData);
        
        echo "✅ 会员记录已创建\n";
    }
    
    // 验证会员记录
    echo "🔍 验证会员记录...\n";
    $membership = Db::name('gf_user_memberships')
        ->where('user_id', $latestUser['id'])
        ->find();
    
    if ($membership) {
        echo "✅ 会员记录验证成功\n";
        echo "   会员ID: {$membership['id']}\n";
        echo "   套餐类型: {$membership['plan_type']}\n";
        echo "   状态: {$membership['status']}\n";
        echo "   开始日期: {$membership['start_date']}\n";
        echo "   结束日期: {$membership['end_date']}\n";
    } else {
        echo "❌ 会员记录验证失败\n";
        exit(1);
    }
    
} catch (\Exception $e) {
    echo "❌ 添加会员数据失败: " . $e->getMessage() . "\n";
    exit(1);
}

echo "🎉 测试会员数据添加完成！\n";